/**
* @Description:（基于百度地图的，使用需引用vue-baidu-map）关键字搜索，拖动,点击地图返回位置组件
* @author NewLore1
* @Date 2021/07/06/10:18
* @LastEditors: 乔
* @LastEditTime: 2021/07/06/10:18
*vue-baidu-map使用文档地址：https://dafrok.github.io/vue-baidu-map/#/zh/start/base
**/
<template>
  <div>
    <el-dialog id="mapDialog" title="关键字搜索，拖动,点击地图返回位置信息" :visible.sync="mapVisible" :fullscreen="false" :close-on-click-modal="false" @close="cancel">
      <!--地图-->
      <div style="display: flex">
        <div style="width: 80%">
          <baidu-map class="bm-views" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" @ready="handler" @click="getClickInfo" @load="syncCenterAndZoom">
            <bm-view class="bm-views" />
            <bm-marker :key="marKey" :position="{lng: center.lng, lat: center.lat }" :raise-on-drag="true" :dragging="true" @dragend="getDragend" />
            <bm-navigation :offset="bmScaleOffset" anchor="BMAP_ANCHOR_TOP_RIGHT" />
            <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :show-address-bar="true" :auto-location="true" @locationSuccess="getPositionSuccess" />
            <bm-map-type :map-types="['BMAP_NORMAL_MAP','BMAP_SATELLITE_MAP','BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_RIGHT" />
            <bm-control :offset="{width: '10px', height: '10px'}">
              <bm-auto-complete v-model="keyword" :sug-style="{zIndex: 999999}">
                <input type="text" placeholder="请输入搜索关键字" class="serachinput">
              </bm-auto-complete>
            </bm-control>
            <bm-local-search :keyword="keyword" :select-first-result="true" :auto-viewport="true" style="width:0px;height:0px;overflow: hidden;" @searchcomplete="searchCompleteClick" />
          </baidu-map>
        </div>

        <!--选择地址-->
        <div class="add-all">
          <div><span class="add-lal">纬度:</span> {{ selectForm.lat }}</div>
          <div><span class="add-lal">经度: </span>{{ selectForm.lng }}</div>
          <div><span class="add-lal">省:</span> {{ selectForm.province }}</div>
          <div><span class="add-lal">市:</span> {{ selectForm.city }}</div>
          <div><span class="add-lal">区:</span> {{ selectForm.district }}</div>
          <div><span class="add-lal">街道:</span> {{ selectForm.street }}</div>
          <div><span class="add-lal">地址:</span> {{ selectForm.address }}</div>
          <div><span class="add-lal">建筑:</span> {{ selectForm.title }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: -30px">
        <el-button type="warning" size="small" icon="el-icon-close" @click.native="cancel">取消</el-button>
        <el-button type="primary" size="small" icon="el-icon-check" @click.native="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { isValidateNull } from '@/utils/validate';
export default {
  props: {
    value: Boolean,
    mapLng: { // 经度
      type: Number,
      default: 0
    },
    mapLat: { // 维度
      type: Number,
      default: 0
    }

  },
  data() {
    return {
      bmScaleOffset: { width: 5, height: 60 }, // 比例尺控件偏离值
      marKey: 1, // 随机数
      mapVisible: true,
      keyword: '',
      /* center: {lng: 113.390028, lat:34.792723},//默认荥阳市政府*/
      center: { lng: '', lat: '' }, // 默认显示位置
      zoom: 15,
      selectForm: {
        title: '', // 建筑
        province: '', // 省
        city: '', // 市
        district: '', // 区
        street: '', // 街道
        address: '', // 地址
        lat: 0, // 纬度
        lng: 0 // 经度
      },
      BMap: '',
      map: ''
    };
  },
  watch: {
    value: function(currentValue) {
      if (currentValue) {
        this.keyword = '';
      }
    }
  },
  created() {
    if (!isValidateNull(this.mapLng) && !isValidateNull(this.mapLat) && this.mapLng !== 0 && this.mapLat !== 0) {
      this.center.lng = this.mapLng;
      this.center.lat = this.mapLat;// 默认显示位置
      this.getAddressList(this.center.lng, this.center.lat);
    }
    this.marKey += 1;
  },
  methods: {
    handler({ BMap, map }) {
      const _this = this; // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
      const geolocation = new BMap.Geolocation();
      _this.BMap = BMap;
      _this.map = map;
      // 传递的值 isValidateNull(this.center.lng) || isValidateNull(this.center.lat)
      if (this.center.lng === 0 && this.center.lat === 0) {
        // 用来获取设备当前位置
        geolocation.getCurrentPosition(function(r) {
          _this.center = { lng: r.longitude, lat: r.latitude }; // 设置center属性值
          _this.autoLocationPoint = { lng: r.longitude, lat: r.latitude }; // 自定义覆盖物
          _this.initLocation = true;
          _this.getAddressList(r.longitude, r.latitude);
        }, { enableHighAccuracy: true });
      } else {
        this.center.lng = this.mapLng;
        this.center.lat = this.mapLat;// 默认显示位置
      }
      window.map = map;
    },

    /** *
     * 地图点击事件。
     */
    getClickInfo(e) {
      map.clearOverlays();
      this.center.lng = e.point.lng;
      this.center.lat = e.point.lat;
      this.getAddressList(e.point.lng, e.point.lat);
      this.marKey += 1;
    },

    /** *
     * 定位成功回调
     */
    getPositionSuccess(e) {
      map.clearOverlays();
      this.center.lng = e.point.lng;
      this.center.lat = e.point.lat;
      this.getAddressList(e.point.lng, e.point.lat);
      this.marKey += 1;
    },
    /** *
     * 完成检索时调用
     */
    searchCompleteClick(e) {
      this.$nextTick(() => {
        if (typeof e === 'undefined') {
          return;
        }
        map.clearOverlays();
        this.selectForm = {
          title: '', // 建筑
          province: '', // 省
          city: '', // 市
          district: '', // 区
          street: '', // 街道
          address: '', // 地址
          lat: 0, // 纬度
          lng: 0 // 经度
        };
        if (!isValidateNull(e.Br[0])) {
          this.center.lng = e.Br[0].point.lng;
          this.center.lat = e.Br[0].point.lat;
          this.getAddressList(e.Br[0].point.lng, e.Br[0].point.lat);
          this.marKey += 1;
        }
      });
    },
    /** *
     * 拖拽结束
     */
    getDragend(e) {
      this.getAddressList(e.point.lng, e.point.lat);
    },

    /** *
     * 页面加载的点
     */
    syncCenterAndZoom(e) {
      const { lng, lat } = e.target.getCenter();
      this.center.lng = lng;
      this.center.lat = lat;
      /*  this.zoom = e.target.getZoom();*/
      this.getAddressList(lng, lat);
    },

    /** *
     * 根据经纬度获取详细地址
     */
    getAddressList(lngValue, latValue) {
      if (!lngValue || !latValue) {
        return;
      }
      const myGeo = new BMap.Geocoder();
      const _this = this;
      myGeo.getLocation(new BMap.Point(lngValue, latValue), function(res) {
        _this.selectForm = {
          title: '', // 建筑
          province: '', // 省
          city: '', // 市
          district: '', // 区
          street: '', // 街道
          address: '', // 地址
          lat: 0, // 纬度
          lng: 0 // 经度
        };
        const addComp = res.addressComponents;
        if (!isValidateNull(res.surroundingPois[0])) { // 获取第一条周围POI信息
          const surround = res.surroundingPois[0].title ? res.surroundingPois[0].title : '';
          _this.selectForm.title = res.surroundingPois[0].address + '(' + surround + ')';
        }
        _this.selectForm.city = addComp.city;
        _this.selectForm.district = addComp.district;
        _this.selectForm.province = addComp.province;
        _this.selectForm.lng = res.point.lng.toFixed(6);
        _this.selectForm.lat = res.point.lat.toFixed(6);
        _this.selectForm.address = res.address;
        _this.selectForm.street = addComp.street + addComp.streetNumber;
      });
    },

    /** *
     * 确定事件
     */
    confirm() {
      this.mapVisible = true;
      this.$emit('map-confirm', this.selectForm);
    },

    // 取消事件
    cancel() {
      this.mapVisible = true;
      this.$emit('cancel', '');
    }
  }
};
</script>

<style scoped>
.bm-views {
  width: 100%;
  height:calc(80vh - 90px)
}

.serachinput{
  width: 300px;
  height: 38px;
  box-sizing: border-box;
  padding: 9px;
  border: 1px solid #dddee1;
  line-height: 20px;
  font-size: 16px;
  color: #333;
  position: relative;
  border-radius: 4px;
  -webkit-box-shadow: #666 0px 0px 10px;
  -moz-box-shadow: #666 0px 0px 10px;
  box-shadow: #666 0px 0px 10px;
}
.add-all {
  width: 200px;
  padding: 10px;
  border: ridge;
  overflow: auto;
  font-size: 13px;
}
.add-all div{
  margin-bottom: 6px;
}
.add-lal{
  font-size: 15px;
  font-weight: 600;
}
</style>

